/*!
 * \file cics_core.h
 *
 * \brief CICS模块主文件
 *
 * All Rights Reserved Copyright (C) 2014 broada,Co.,Ltd.
 *
 * \version 1.0
 * \author songbb
 * \date 2015/10/07
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/types.h>

#include "frcomm.h"
#include "frstr.h"
#include "frhash2.h"
#include "frmem.h"
#include "frlog.h"
#include "frsutl.h"
#include "frreport_comm.h"

#include "conntrack.h"
#include "frct_comm.h"
#include "frversion.h"

#include "cics_comm.h"
#include "cics_core.h"
#include "cics_header.h"
#include "cics_packet.h"
#include "cics_gateway.h"
#include "cics_eci.h"

/*******************************************************************************
*  FUNC     :  Cics Session初始化
*  ARGS     :  *p_st_session                            (L7层session信息)
*  RTN      :  0                                        (FR_SUCC)
*              1                                        (FR_FAIL)
*  NOTE     :
*******************************************************************************/
FR_STATIC int __cics_private_session_init(L7_session *p_st_session)
{
    CICS_PRINT_INFO("session init\n");
    L7session_cics_private *p_st_cics_private = NULL;      // CICS的私有信息
    L7session_cics *p_st_cics_sess = NULL;                 // CICS的私有session信息
    L7_cics_packet *p_st_cics_packet = NULL;               // CICS格式的packet包
    Frhash_header *p_hash_stmt = NULL;                     // CICS的statement信息结构

    // 1. 初始化Cics的私有session信息
    if ((p_st_cics_sess = (L7session_cics *) frmalloc(sizeof(L7session_cics))) == NULL)
    {
        CICS_MALLOCK_ERR;
        goto error;
    }
    memset(p_st_cics_sess, 0x00, sizeof(L7session_cics));

    // 2. 初始化Cics格式的packet包
    if ((p_st_cics_packet = (L7_cics_packet *) frmalloc(sizeof(L7_cics_packet))) == NULL)
    {
        CICS_MALLOCK_ERR;
        goto error;
    }
    memset(p_st_cics_packet, 0x00, sizeof(L7_cics_packet));
    if (cics_init_packet(p_st_cics_packet) != FR_SUCC)
        goto error;

    // 3. 初始化statement hash
    if ((p_hash_stmt = (Frhash_header *) frmalloc(sizeof(Frhash_header))) == NULL)
    {
        CICS_MALLOCK_ERR;
        goto error;
    }
    memset(p_hash_stmt, 0x00, sizeof(Frhash_header));
    if (frhash2_create(p_hash_stmt, APM_CICS_HASH_SIZE) != FR_SUCC)
    {
        CICS_FRLOG_ERROR("frhash2_create fail");
        goto error;
    }

    // 4. 创建和初始化Cics的私有信息
    if ((p_st_cics_private = (L7session_cics_private *) frmalloc(sizeof(L7session_cics_private))) == NULL)
    {
        CICS_MALLOCK_ERR;
        goto error;
    }
    memset(p_st_cics_private, 0x00, sizeof(L7session_cics_private));
    p_st_cics_private->p_st_sess = p_st_cics_sess;
    p_st_cics_private->p_st_cics_packet = p_st_cics_packet;
    p_st_cics_private->p_st_session = p_st_session;
    p_st_cics_private->p_hash_stmt = p_hash_stmt;

    // 5. 设置L7_session的p_session_private信息
    frct_set_session_private(p_st_session, (void *)p_st_cics_private);

    return FR_SUCC;
error:
    cics_free((void **) &p_st_cics_sess);
    if (p_st_cics_packet != NULL)
    {
        bytebuff_free(&(p_st_cics_packet->p_st_packet));
        cics_free((void **) &p_st_cics_packet);
    }
    frhash2_free2(p_hash_stmt, frlist_node_data_free);
    cics_free((void **) &p_st_cics_private);
    return FR_FAIL;
}

/*******************************************************************************
*  FUNC     :  分析数据方向
*  ARGS     :  ui_flow_type                             (iFlowType)
*  RTN      :  0x00                                     (FR_DIRECT_UNKNOWN)
*              0x02                                     (FR_DIRECT_SRV2CLIENT)
*              0x03                                     (FR_DIRECT_CLIENT2SRV)
*  NOTE     :
*******************************************************************************/
FR_STATIC int __cics_analyze_direct(unsigned int ui_flow_type)
{
    switch (ui_flow_type)
    {
        case APM_CICS_FLOW_REQUEST:
        case APM_CICS_FLOW_CLOSE:
        case APM_CICS_FLOW_PONG:
            return FR_DIRECT_CLIENT2SRV;
        case APM_CICS_FLOW_REPLY:
//        case APM_CICS_FLOW_EXCEPTION:
        case APM_CICS_FLOW_PING:
        case APM_CICS_FLOW_CONFIRM:
            return FR_DIRECT_SRV2CLIENT;
        default:
            return FR_DIRECT_UNKNOWN;
    }
}

int cics_detect(Conntrack *p_st_conn
            , Apm_packet *p_st_packet)
{
    CICS_PRINT_INFO("cics_detect\n");
    int i_analyzed_direct = 0;
    Cics_header st_cics_header;
    memset(&st_cics_header, 0x00, sizeof(st_cics_header));

#if APM_CICS_DBG
    char arr_ip_src[56], arr_ip_dst[56];
    snprintf(arr_ip_src, sizeof(arr_ip_src), "%s", int_ntoa(p_st_packet->src_ip));
    snprintf(arr_ip_dst, sizeof(arr_ip_src), "%s", int_ntoa(p_st_packet->dst_ip));
    CICS_PRINT_TIMEVAL("PacketIn", p_st_packet->st_timestamp);
    CICS_PRINT_DBG("Src:[%s:%d] Dest:[%s:%d] Length:[%u]\n", arr_ip_src, p_st_packet->src_port, arr_ip_dst, p_st_packet->dst_port, p_st_packet->ui_payload_len);
#endif

    int i_ret = cics_header_detect(p_st_packet->p_payload, p_st_packet->ui_payload_len);
    if (i_ret == APM_L7_IS_YES)
    {
        // 设置方向
        if (p_st_packet->i_direction == FR_DIRECT_UNKNOWN || frct_get_direct_known(p_st_conn) == FR_DIRECT_UNKNOWN)
        {
            if (cics_header_unpack(p_st_packet->p_payload, p_st_packet->ui_payload_len, &st_cics_header) != FR_SUCC)
                return APM_L7_IS_UNKNOWN;
            i_analyzed_direct = __cics_analyze_direct(st_cics_header.ui_flow_type);
            if (i_analyzed_direct == FR_DIRECT_CLIENT2SRV)
            {
                if (frcap_set_cs_srv(p_st_conn, p_st_packet->dst_ip, p_st_packet->dst_port) != FR_SUCC)
                    return APM_L7_IS_UNKNOWN;
            }
            else if (i_analyzed_direct == FR_DIRECT_SRV2CLIENT)
            {
                if (frcap_set_cs_srv(p_st_conn, p_st_packet->src_ip, p_st_packet->src_port) != FR_SUCC)
                    return APM_L7_IS_UNKNOWN;
            }
            else
            {
                CICS_PRINT_EMERG("Can not analyze direction\n");
                return APM_L7_IS_UNKNOWN;
            }
        }
    }

    if (i_ret == APM_L7_IS_UNKNOWN)
        CICS_PRINT_ERR("detect unknown\n\n");
    else
        CICS_PRINT_ERR("detect yes\n\n");

    return i_ret;
}

int cics_analyze(Conntrack *p_st_conn
                , Apm_packet *p_st_packet
                , Frhash_header *p_st_hash_report)
{
    CICS_PRINT_INFO("cics_analyze\n");
    L7_session *p_st_session = NULL;
    L7session_cics_private *p_st_session_private = NULL;
    L7session_cics *p_st_sess = NULL;
    L7_cics_packet *p_st_cics_packet = NULL;
    int i_unfragmented_ret = 0;
    int i_analyze_ret = 0;                  // 本函数的返回值
    char arr_ip_src[56], arr_ip_dst[56];

    if(p_st_conn == NULL || p_st_packet == NULL
      || p_st_hash_report == NULL)
        return APM_L7_ANALYZE_FAIL;

    p_st_session = frct_get_session(p_st_conn);
    snprintf(arr_ip_src, sizeof(arr_ip_src), "%s", int_ntoa(p_st_packet->src_ip));
    snprintf(arr_ip_dst, sizeof(arr_ip_src), "%s", int_ntoa(p_st_packet->dst_ip));

    CICS_PRINT_TIMEVAL("PacketIn", p_st_packet->st_timestamp);
    CICS_PRINT_DBG("Src:[%s:%d] Dest:[%s:%d] SessionID:[%s]\n", arr_ip_src, p_st_packet->src_port, arr_ip_dst, p_st_packet->dst_port, p_st_session->arr_session_id);

    /*
    * 如果入力p_st_packet是FIN包, 说明本次connection结束,
    * 释放本次session信息. 如果入力p_st_packet是SYN包,说明新的
    * connection开始了, 释放上次可能残留的session信息
    */
    if (p_st_packet->em_analyz_cmd == FRANALYZ_CMD_FIN || p_st_packet->em_analyz_cmd == FRANALYZ_CMD_SYN)
    {
        if (p_st_packet->em_analyz_cmd == FRANALYZ_CMD_SYN)
            CICS_PRINT_INFO("SYN PACKET\n");
        else if (p_st_packet->em_analyz_cmd == FRANALYZ_CMD_FIN)
            CICS_PRINT_INFO("FIN PACKET\n");
        if (p_st_session->p_session_private != NULL)
        {
            cics_session_destory(p_st_session->p_session_private);
            p_st_session->p_session_private = NULL;
        }
        CICS_PRINT("### i_analyze_ret:[%d]\n\n", APM_L7_ANALYZE_SUCC);
        return APM_L7_ANALYZE_SUCC;
    }

    // 本次链路的第一个有效packet包,创建链路
    if (p_st_session->p_session_private == NULL)
    {
        // 初始化Cics的session数据
        if (__cics_private_session_init(p_st_session) != FR_SUCC)
            goto cics_analyze_fail;

        // 设置session uuid
        fruuid(p_st_session->arr_session_id);
    }

    // 打印方向
    switch (p_st_packet->i_direction)
    {
        case FR_DIRECT_CLIENT2SRV:
            CICS_PRINT("client["KLIMEGREEN"%s:%d"RESET"] to server["KLIMEGREEN"%s:%d"RESET"] ["KYELLOW"%d"RESET"] ->>>>>>>>>>>>>>>>>>>>>>>\n",
                      arr_ip_src,
                      p_st_packet->src_port,
                      arr_ip_dst,
                      p_st_packet->dst_port,
                      p_st_packet->ui_payload_len);
            break;
        case FR_DIRECT_SRV2CLIENT:
            CICS_PRINT("server["KLIMEGREEN"%s:%d"RESET"] to client["KLIMEGREEN"%s:%d"RESET"] ["KYELLOW"%d"RESET"] <<<<<<<<<<<<<<<<<<<<<<<-\n",
                      arr_ip_src,
                      p_st_packet->src_port,
                      arr_ip_dst,
                      p_st_packet->dst_port,
                      p_st_packet->ui_payload_len);
            break;
        default:
            CICS_PRINT("unknown direction, src["KLIMEGREEN"%s:%d"RESET"], dest["KLIMEGREEN"%s:%d"RESET"]\n",
                      arr_ip_src,
                      p_st_packet->src_port,
                      arr_ip_dst,
                      p_st_packet->dst_port);
            goto cics_analyze_fail;
    }

    p_st_session_private = (L7session_cics_private *) frct_get_session_private(p_st_session);
    p_st_sess = p_st_session_private->p_st_sess;
    p_st_cics_packet = p_st_session_private->p_st_cics_packet;

    i_unfragmented_ret = cics_packet_unfragment(p_st_sess, p_st_packet, p_st_cics_packet);
    if (i_unfragmented_ret == APM_CICS_CHECK_FRAGMENT_NEED_NEXT_PACKET)
        goto cics_analyze_todo;
    else if (i_unfragmented_ret == APM_CICS_CHECK_FRAGMENT_ERROR)
        goto cics_analyze_fail;

    switch (p_st_cics_packet->em_req_type)
    {
        case APM_CICS_REQTYPE_BASE:
            if (cics_gateway(p_st_conn, p_st_sess, p_st_cics_packet, p_st_hash_report) == FR_SUCC)
            {
                i_analyze_ret = (p_st_packet->i_direction == FR_DIRECT_CLIENT2SRV) ?
                                APM_L7_ANALYZE_SET_REQ(APM_L7_ANALYZE_SUCC) : APM_L7_ANALYZE_SET_RESP(APM_L7_ANALYZE_SUCC);
                goto cics_analyze_success;
            }
            goto cics_analyze_fail;

        case APM_CICS_REQTYPE_ECI:
            if (p_st_packet->i_direction == FR_DIRECT_CLIENT2SRV)
            {
                if (cics_eci_req(p_st_conn, p_st_sess, p_st_cics_packet, p_st_hash_report) == FR_SUCC)
                {
                    i_analyze_ret = APM_L7_ANALYZE_SET_REQ(APM_L7_ANALYZE_SUCC);
                    goto cics_analyze_success;
                }
            }
            else
            {
                if (cics_eci_resp(p_st_conn, p_st_sess, p_st_cics_packet, p_st_hash_report) == FR_SUCC)
                {
                    i_analyze_ret = APM_L7_ANALYZE_SET_RESP(APM_L7_ANALYZE_SUCC);
                    goto cics_analyze_success;
                }
            }
            goto cics_analyze_fail;

        case APM_CICS_REQTYPE_XA:
        case APM_CICS_REQTYPE_EPI:
        case APM_CICS_REQTYPE_ESI:
        case APM_CICS_REQTYPE_AUTH:
        case APM_CICS_REQTYPE_CICSCP:
        case APM_CICS_REQTYPE_UNKNOWN:
            printf("REQTYPE:[%d]\n", p_st_cics_packet->em_req_type);
            CICS_PRINT_CRIT("REQTYPE:[%d]\n", p_st_cics_packet->em_req_type);
            break;

        default:
            goto cics_analyze_fail;
    }

cics_analyze_todo:
    CICS_PRINT("### i_analyze_ret todo:[%d]\n\n", APM_L7_ANALYZE_TODO);
    return APM_L7_ANALYZE_TODO;

cics_analyze_success:
    CICS_PRINT("### i_analyze_ret success:[%d]\n\n", i_analyze_ret);
    return i_analyze_ret;

cics_analyze_fail:
    if (cics_packet_is_in_fragment(p_st_cics_packet))
    {
        if (bytebuff_setPosition(p_st_cics_packet->p_st_packet, 0) != FR_SUCC)
        {
            p_st_cics_packet->fragment_state = APM_CICS_FRAGMENT_INIT;
            return APM_L7_ANALYZE_FAIL;
        }
        goto cics_analyze_todo;
    }
    else
    {
        CICS_PRINT_PACKET("error packet", p_st_cics_packet);
        cics_init_packet(p_st_cics_packet);
    }

    CICS_PRINT_EMERG("### i_analyze_ret fail:[%d]\n\n", APM_L7_ANALYZE_FAIL);
    return APM_L7_ANALYZE_FAIL;
}

/*******************************************************************************
*  FUNC     :  释放 L7session_cics
*  ARGS     :  **pp_st_session              (L7session_cics)
*  RTN      :  void
*  NOTE     :
*******************************************************************************/
FR_STATIC void __cics_destroy_session(L7session_cics **pp_st_session)
{
    if (pp_st_session == NULL || *pp_st_session == NULL)
        return;

    L7session_cics *p_st_sess = *pp_st_session;
    cics_free((void **) &(p_st_sess->p_server));
    cics_free((void **) &(p_st_sess->p_userid));
    cics_free((void **) &(p_st_sess->p_encoding));
    cics_free((void **) pp_st_session);
    return;
}

/*******************************************************************************
*  FUNC     :  释放 L7_cics_packet
*  ARGS     :  **pp_st_cics_packet              (L7_cics_packet)
*  RTN      :  void
*  NOTE     :
*******************************************************************************/
FR_STATIC void __cics_destroy_packet(L7_cics_packet **pp_st_cics_packet)
{
    if (pp_st_cics_packet == NULL || *pp_st_cics_packet == NULL)
        return;

    L7_cics_packet *p_st_cics_packet = *pp_st_cics_packet;
    bytebuff_free(&(p_st_cics_packet->p_st_packet));
    cics_free((void **) pp_st_cics_packet);
    return;
}

/*******************************************************************************
*  FUNC     :  释放 L7_cics_stmt
*  ARGS     :  **pp_st_cics_stmt              (L7_cics_stmt)
*  RTN      :  void
*  NOTE     :
*******************************************************************************/
FR_STATIC void __cics_destroy_stmt(Frhash_header *p_hash_stmt)
{
    frhash2_free2(p_hash_stmt, frlist_node_data_free);
}

int cics_session_destory(void *p_st_session_private_in)
{
    CICS_PRINT(KBLUE "\ncics_session_destory run\n" RESET);
    if (p_st_session_private_in == NULL)
        return FR_SUCC;

    L7session_cics_private *p_st_private = (L7session_cics_private *) p_st_session_private_in;

    __cics_destroy_session(&(p_st_private->p_st_sess));

    __cics_destroy_packet(&(p_st_private->p_st_cics_packet));

    __cics_destroy_stmt(p_st_private->p_hash_stmt);

    frreport_body_l7list_free(&(p_st_private->p_report_comm));
    frreport_body_l7list_free(&(p_st_private->p_report_req));

    cics_free((void **) &p_st_private);

    CICS_PRINT_INFO("leave cics_session_destory\n");
    return FR_SUCC;
}
